#!/usr/bin/env bash
# proxy startup bash script

CUR_PATH="$(dirname "${BASH_SOURCE[0]}")"
# shellcheck source=./common.sh
source "${CUR_PATH}/common.sh"

log:info "Starting node as transaction manager proxy"

# shellcheck source=./initialize_env_dependencies
source "${CUR_PATH}/initialize_env_dependencies"

# initialize the gtm_proxy manager
initgtm -D "${PGDATA}" -Z gtm_proxy
assert $? "Failed to initialize gtm proxy" || exit $?

# config
# shellcheck source=./initialize_networks
source "${CUR_PATH}/initialize_networks" || exit $?
# shellcheck source=./initialize_node_config
source "${CUR_PATH}/initialize_node_config" || exit $?

# start the proxy.
PROXY_ID="${POD_CLUSTER_INDEX}"
PROXY_HOST="${POD_IP}"

log:info "looking for GTM..."
"${CUR_PATH}/wait_for_connection" "${PG_GTM_HOST}" "${PG_GTM_PORT}"
assert $? "Timed out while waiting for GTM. Database not ready, cannot start proxy." || exit $?

log:info "Starting proxy ${PROXY_ID} @ ${PROXY_HOST}:${PG_GTM_PORT} -> ${PG_GTM_HOST}:${PG_GTM_PORT} .."
gtm_proxy \
  -D "${PGDATA}" \
  -h "${PROXY_HOST}" \
  -p "${PG_GTM_PORT}" \
  -i "${PROXY_ID}" \
  -s "${PG_GTM_HOST}" \
  -t "${PG_GTM_PORT}" \
  -n "${PROXY_THREAD_COUNT}" \
  -l /dev/stdout
assert $? "Cannot start GTM proxy" || exit $?
